package com.wdl.modules.myhouse.security.entity;

import com.wdl.modules.myhouse.entity.sys.SysRoleEntity;
import com.wdl.modules.myhouse.security.common.SecurityConstant;
import io.swagger.models.auth.In;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author 昏昏的君
 */
@Slf4j
@NoArgsConstructor
@Data
@ToString
public class UserInfo implements UserDetails, Serializable {

    private Integer id;
    private String username;
    private String password;
    private String token;
    private Integer status;
    private Integer userLocked;
    private Integer credentialExpired;
    private Integer accountExpired;
    private List<SysRoleEntity> roles;


    public static List<SysRoleEntity> defaultUserRole() {
        ArrayList<SysRoleEntity> roleEntities = new ArrayList<SysRoleEntity>();
        roleEntities.add(new SysRoleEntity(1, "ROLE_USER", "基本角色"));
        return roleEntities;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SysRoleEntity> roles = getRoles();
        if (roles != null && roles.size() > 0) {
            return roles.stream().map(role -> new SimpleGrantedAuthority(role.getRoleName())).collect(Collectors.toList());
        }
        return null;
    }


    @Override
    public boolean isAccountNonExpired() {
        if (this.accountExpired != null && this.accountExpired.equals(SecurityConstant.ACCOUNT_UNEXPIRED)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean isAccountNonLocked() {
        if (this.userLocked != null && this.userLocked.equals(SecurityConstant.ACCOUNT_UNLOCKED)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        if (this.credentialExpired != null && this.credentialExpired.equals(SecurityConstant.CERTIFICATE_UNEXPIRED)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean isEnabled() {
        if (this.status != null && this.status.equals(SecurityConstant.ACCOUNT_ENABLED)) {
            return true;
        }
        return false;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }
}
